package com.whmall.service.crm.module.company.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.whmall.common.enumeration.YesNoEnum;
import com.whmall.component.common.ObjectConverter;
import com.whmall.component.enumeration.CompanyLogOperationTypeEnum;
import com.whmall.component.enumeration.OperatorTypeEnum;
import com.whmall.service.crm.entity.dto.company.SupplierAccountReqDTO;
import com.whmall.service.crm.module.company.dao.CompanyLogMapper;
import com.whmall.service.crm.module.company.dao.SupplierAccountMapper;
import com.whmall.service.crm.module.company.entity.CompanyLogDO;
import com.whmall.service.crm.module.company.entity.SupplierAccountDO;
import com.whmall.service.crm.module.company.service.CompanySupplierService;
import com.whmall.service.crm.util.TimesUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.Assert;

import java.util.Date;
import java.util.List;
import java.util.Objects;

/**
 * Description TODO
 * Author yangkuan
 * Date 2020/8/4 14:23
 **/
@Service
public class CompanySupplierServiceImpl implements CompanySupplierService {

    @Autowired
    private SupplierAccountMapper supplierAccountMapper;
    @Autowired
    private CompanyLogMapper companyLogMapper;
    @Autowired
    private CompanySupplierAddValidator companySupplierAddValidator;

    @Autowired
    private final ObjectConverter<SupplierAccountReqDTO, SupplierAccountDO> supplierAccountReqDTO2SupplierAccountReqDO;

    public CompanySupplierServiceImpl(ObjectConverter<SupplierAccountReqDTO, SupplierAccountDO>
                                              supplierAccountReqDTO2SupplierAccountReqDO) {
        this.supplierAccountReqDTO2SupplierAccountReqDO = supplierAccountReqDTO2SupplierAccountReqDO;
    }

    @Override
    public List<SupplierAccountDO> queryCompanySupplierById(Long companyId) {

        if (companyId == null || companyId == 0) {
            throw new IllegalArgumentException("请求公司ID不能为空");
        }
        List<SupplierAccountDO> supplierAccountDOS = supplierAccountMapper
                .selectSupplierByCompanyId(companyId);
        return supplierAccountDOS;
    }

    @Override
    @Transactional
    public Long insertSupplierAccount(SupplierAccountReqDTO reqDTO) {

        Assert.notNull(reqDTO.getCompanyId(), "请求公司ID不能为空");

        companySupplierAddValidator.validate(reqDTO);

        Long accountCount = supplierAccountMapper.selectCount(new LambdaQueryWrapper<SupplierAccountDO>()
                .eq(SupplierAccountDO::getDeleted, 0)
                .eq(SupplierAccountDO::getCompanyId, reqDTO.getCompanyId()));
        if (accountCount == 0) {
            reqDTO.setDefaultAccount(1);
        }
        SupplierAccountDO account = supplierAccountReqDTO2SupplierAccountReqDO
                .convert(reqDTO);
        // 创建者、创建时间
        account.setCreateId(reqDTO.getEmployeeId());
        account.setCreateTime(new Date());
        //是否删除
        account.setDeleted(0);

        if (reqDTO.getDefaultAccount() == 1) {

            SupplierAccountDO supplierDefaultAccountDO = supplierAccountMapper
                    .selectDefaultSupplier(reqDTO.getCompanyId(), 1L);

            if (supplierDefaultAccountDO != null) {
                supplierDefaultAccountDO.setDefaultAccount(TimesUtils.getSecondTimestamp(new Date()));
                supplierAccountMapper.updateByIdSelective(supplierDefaultAccountDO);
            }
        }


        if (reqDTO.getDefaultAccount() != 1) {
            account.setDefaultAccount(TimesUtils.getSecondTimestamp(new Date()));
        }
        try {
            supplierAccountMapper.insertSelective(account);
        } catch (DuplicateKeyException e) {
            throw new IllegalArgumentException("请勿重复添加供应商收款账号");
        }
        //公司日志
        CompanyLogDO logDO = CompanyLogDO.builder()
                .companyId(account.getCompanyId())
                .createType(OperatorTypeEnum.EMPLOYEE.getValue())
                .createId(reqDTO.getEmployeeId())
                .operationType(CompanyLogOperationTypeEnum.UPDATE_SUPPLIER_INFORMATION.getValue())
                .operationDesc1("新增银行账户（银行名称“" + account.getBankName() + "”账号“" + account.getAccount()
                        + "”户名“" + account.getAccountName() + "”")
                .ip(null).createTime(new Date()).build();
        companyLogMapper.insertSelective(logDO);
        return account.getId();
    }

    @Override
    @Transactional
    public void updateCompanySupplier(Long supplierId, SupplierAccountReqDTO supplierAccountReqDTO) {

        Assert.notNull(supplierAccountReqDTO.getCompanyId(), "请求公司ID不能为空");

        Assert.notNull(supplierId, "请求ID不能为空");

        companySupplierAddValidator.validate(supplierAccountReqDTO);

        SupplierAccountDO supplierAccountDO = supplierAccountReqDTO2SupplierAccountReqDO
                .convert(supplierAccountReqDTO);

        supplierAccountDO.setId(supplierId);
        // 更改者、更改时间
        supplierAccountDO.setUpdateId(supplierAccountReqDTO.getEmployeeId());
        supplierAccountDO.setUpdateTime(new Date());

        //是否删除
        supplierAccountDO.setDeleted(0);

        if (supplierAccountReqDTO.getDefaultAccount() == 1) {

            SupplierAccountDO supplierDefaultAccountDO = supplierAccountMapper
                    .selectDefaultSupplier(supplierAccountReqDTO.getCompanyId(), 1L);

            if (supplierDefaultAccountDO != null) {
                supplierDefaultAccountDO.setDefaultAccount(TimesUtils.getSecondTimestamp(new Date()));
                supplierAccountMapper.updateByIdSelective(supplierDefaultAccountDO);
            }
        }

        if (supplierAccountReqDTO.getDefaultAccount() != 1) {
            supplierAccountDO.setDefaultAccount(TimesUtils.getSecondTimestamp(new Date()));
        }

        supplierAccountMapper.updateByIdSelective(supplierAccountDO);
    }

    @Override
    @Transactional
    public void setDefaultSupplier(Long supplierId, Long reqId) {

        Assert.notNull(supplierId, "请求ID不能为空");
        SupplierAccountDO supplierAccountDO = supplierAccountMapper
                .selectById(supplierId);
        Long companyId = supplierAccountDO.getCompanyId();

        SupplierAccountDO supplierDefaultAccountDO = supplierAccountMapper
                .selectDefaultSupplier(companyId, 1L);

        if (supplierDefaultAccountDO != null) {
            supplierDefaultAccountDO.setDefaultAccount(TimesUtils.getSecondTimestamp(new Date()));
            supplierDefaultAccountDO.setUpdateId(reqId);
            supplierDefaultAccountDO.setUpdateTime(new Date());
            supplierAccountMapper.updateByIdSelective(supplierDefaultAccountDO);
        }

        if (supplierDefaultAccountDO == null || !supplierAccountDO.getId().equals(supplierDefaultAccountDO.getId())) {
            // 更改者、更改时间
            supplierAccountDO.setUpdateId(reqId);
            supplierAccountDO.setUpdateTime(new Date());
            if (Objects.equals(supplierAccountDO.getDefaultAccount(), YesNoEnum.YES.getCode())) {
                supplierAccountDO.setDefaultAccount((int) (System.currentTimeMillis() / 1000));
            } else {
                supplierAccountDO.setDefaultAccount(1);
            }
            supplierAccountMapper.updateByIdSelective(supplierAccountDO);
        }

    }

}
